import { AppDispatch, useAppSelector } from '@/store';
import {
  addUserChannelAction,
  delUserChannelByIdAction,
  getAllChannelAction,
  getUserChannelAction,
  setCurrentIdAction,
} from '@/store/action/channel';
import { Popup, Tabs, Toast } from 'antd-mobile';
import React, { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import Icon from '../Icon';
import styles from './index.module.scss';
import { differenceBy } from 'lodash';
import { ChannelType } from '@/store/reducer/channel';
import { hasToken, setLocalChannels } from '@/utils/storage';
import { useHistory } from 'react-router-dom';

export default function Channel() {
  const dispatch = useDispatch();

  const history = useHistory();

  useEffect(() => {
    dispatch(getAllChannelAction());
    dispatch(getUserChannelAction());
  }, [dispatch]);

  const { userList, allList, currentId } = useAppSelector((state) => state.channel);
  const [visible, setVisible] = useState(false);
  const [editable, setEditable] = useState(false);

  const restList = differenceBy(allList, userList, 'id');

  const handleDelById = async (id: number) => {
    if (id === 0) {
      Toast.show({ content: '不能删除推荐频道' });
      return;
    }

    if (userList.length === 5) {
      Toast.show({ content: '至少保留5个频道' });
      return;
    }

    if (hasToken()) {
      await dispatch(delUserChannelByIdAction(id));
      Toast.show({ content: '删除成功' });
      return;
    }
    const newUserList = userList.filter((item) => {
      return item.id !== id;
    });
    setLocalChannels(newUserList);
    (dispatch as AppDispatch)({ type: 'channel/saveUserList', payload: newUserList });
    Toast.show({ content: '删除成功' });
  };

  const handleAdd = async (newChannel: ChannelType) => {
    if (hasToken()) {
      await dispatch(addUserChannelAction(newChannel));
      Toast.show({ content: '关注成功' });
      return;
    }

    const newList = [...userList, newChannel];
    setLocalChannels(newList);
    (dispatch as AppDispatch)({ type: 'channel/add', payload: newChannel });
    Toast.show({ content: '关注成功' });
  };

  return (
    <div className={styles.root}>
      <Tabs
        activeKey={String(currentId)}
        onChange={(key) => dispatch(setCurrentIdAction(Number(key)))}
      >
        {userList.map((item) => (
          <Tabs.Tab title={item.name} key={item.id} />
        ))}
      </Tabs>
      <div className="right">
        <Icon type="iconbtn_search" onClick={() => history.push('/search')} />

        <Icon type="iconbtn_channel" onClick={() => setVisible(true)} />
      </div>
      <Popup visible={visible} position="left" bodyClassName={styles.channelPopup}>
        <div className="channel-header">
          <Icon
            type="iconbtn_channel_close"
            onClick={() => {
              setVisible(false);
              setEditable(false);
            }}
          />
        </div>

        <div className="channel-content">
          <div className="channel-item edit">
            <div className="channel-item-header">
              <span className="channel-item-title">我的频道</span>
              <span className="channel-item-title-extra">点击删除频道</span>
              <span className="channel-item-edit" onClick={() => setEditable(!editable)}>
                {editable ? '完成' : '编辑'}
              </span>
            </div>

            <div className="channel-list">
              {userList.map((item) => (
                <span key={item.id} className="channel-list-item">
                  {item.name}
                  {editable && (
                    <Icon type="iconbtn_tag_close" onClick={() => handleDelById(item.id)} />
                  )}
                </span>
              ))}
            </div>
          </div>

          <div className="channel-item">
            <div className="channel-item-header">
              <span className="channel-item-title">频道推荐</span>
              <span className="channel-item-title-extra">点击添加频道</span>
            </div>
            <div className="channel-list">
              {restList.map((item) => (
                <span key={item.id} className="channel-list-item" onClick={() => handleAdd(item)}>
                  + {item.name}
                </span>
              ))}
            </div>
          </div>
        </div>
      </Popup>
    </div>
  );
}
